﻿using Microsoft.AspNetCore.Http;
using XYS.Core.Util.Helper;

namespace XYS.Core.Util;
public static partial class Extention
{
    /// <summary>
    /// 获取真实Ip
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public static string GetRemoteIpAddress(this HttpRequest request)
    {
        string ip = request.Headers["X-Forwarded-For"].FirstOrDefault();

        if (string.IsNullOrEmpty(ip))
        {
            ip = request.Headers["X-Real-IP"].FirstOrDefault();
        }

        if (string.IsNullOrEmpty(ip))
        {
            ip = request.HttpContext.Connection.RemoteIpAddress.ToString();
        }

        return ip;
    }


    /// <summary>
    /// 添加token
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="token">token内容</param>
    /// <param name="headerKey">token在header中key的名字</param>
    /// <returns></returns>
    public static HttpHelper.HttpRequestModel AddToken(this HttpHelper.HttpRequestModel request, string token, string headerKey = "Authorization")
    {
        if (string.IsNullOrWhiteSpace(headerKey)) return request;

        request.Headers ??= new Dictionary<string, string>()
        {
            [headerKey] = token
        };

        if (request.Headers.Any(x => x.Key.ToLower() == headerKey.ToLower()))
            request.Headers.Remove(request.Headers.FirstOrDefault(x => x.Key.ToLower() == headerKey.ToLower()));

        request.Headers.Add(new KeyValuePair<string, string>(headerKey, token));
        return request;
    }

}
